package com.fxu.gen;

import javax.validation.constraints.NotNull;

/**
 * 自定义字符串累加类
 * @author fangxu
 * @version 1.0.0
 */
public class StrBuf {
    private StringBuffer buffer = new StringBuffer();
    private static final String ONE_TAB = "    ";
    private static final String VUE_ONE_TAB = "  ";
    private boolean isVue = false;

    public StrBuf() {}

    public StrBuf(@NotNull Object object) {
        buffer.append(object);
    }

    public StrBuf(boolean isVue) {
        this.isVue = isVue;
    }

    public StrBuf(boolean isVue, @NotNull Object object) {
        this.isVue = isVue;
        buffer.append(object);
    }

    public synchronized StrBuf append(Object line) {
        buffer.append(line);
        return this;
    }

    public int length() {
        return buffer.length();
    }

    public synchronized StrBuf append(int tab, @NotNull Object format, Object ... args) {
        buffer.append(tabStr(tab)).append(format(format, args)).append("\n");
        return this;
    }

    public synchronized StrBuf replace(@NotNull CharSequence target, @NotNull CharSequence replacement) {
        this.buffer = new StringBuffer(buffer.toString().replace(target, replacement));
        return this;
    }

    public synchronized StrBuf moveLast() {
        if (buffer.toString().endsWith("\n ") || buffer.toString().endsWith(", ")) {
            buffer.setLength(buffer.length() - 2);
        }
        if (buffer.toString().endsWith("\n") || buffer.toString().endsWith(",")) {
            buffer.setLength(buffer.length() - 1);
        }
        return this;
    }

    public synchronized String toString() {
        return buffer.toString();
    }

    public synchronized StringBuffer toBuffer() {
        return buffer;
    }

    public String tabStr(int tab) {
        if (tab <= 0) {
            return "";
        }
        StringBuilder buffer = new StringBuilder();
        for (int i = 1; i <= tab; i++) {
            buffer.append(isVue ? VUE_ONE_TAB : ONE_TAB);
        }
        return buffer.toString();
    }

    public static String tabStr(int tab, boolean isVue) {
        if (tab <= 0) {
            return "";
        }
        StringBuilder buffer = new StringBuilder();
        for (int i = 1; i <= tab; i++) {
            buffer.append(isVue ? VUE_ONE_TAB : ONE_TAB);
        }
        return buffer.toString();
    }

    public static String format(final Object tpl, Object ... args) {
        String temp = String.valueOf(tpl);
        if (args != null && args.length > 0) {
            for (int i = 1, len = args.length; i <= len; i++) {
                temp = temp.replace("{"+i+"}", args[i-1] == null ? "" : String.valueOf(args[i-1]));
            }
        }
        return temp;
    }
}
